<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Abstracts the data store. The data store can be retrieved with
 * getDataStore(), which will return an object that implements DMDataStore.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMDataStoreFactory {

	/** @var DMDataStore */
	private static $data_store;

	/**
	 * @return DMDataStore object, or null if not available
	 * @throws DMDataStoreException
	 */
	public static function getDataStore() {
		$ds = (strlen(self::$data_store) > 0)
			? self::$data_store : DMConfigIni::getInstance()->getString(
					"dmbridge.database.engine");
		switch ($ds) {
			case 'pdo_mysql':
				self::setDataStore("pdo_mysql");
				return DMMySQLDataStore::getInstance();
				break;
			case 'pdo_sqlite':
				self::setDataStore("pdo_sqlite");
				return DMSQLiteDataStore::getInstance();
				break;
		}
		return null;
	}

	/**
	 * Used to override the current data store in config.xml.
	 *
	 * @param name Data store name (one of the constants in DMDataStoreType)
	 * @throws DMDataStoreException
	 */
	public static final function setDataStore($name) {
		if (!in_array($name, DMDataStoreType::getAll())) {
			throw new DMDataStoreException(
				DMLocalizedString::getString("UNAVAILABLE_DATA_STORE"));
		}
		self::$data_store = $name;

		// cleanup
		DMMySQLDataStore::destroyInstance();
		DMSQLiteDataStore::destroyInstance();
	}

}
